import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../features/training_records/bloc/training_history_bloc.dart';
import '../features/training_records/bloc/training_history_event.dart';
import '../features/training_records/bloc/training_history_state.dart';
import '../features/training_records/model/training_record.dart';

class AudioTrainingResultPage extends StatefulWidget {
  final List<bool> correctness;
  final List<int> responseTimes;

  const AudioTrainingResultPage({
    super.key,
    required this.correctness,
    required this.responseTimes,
  });

  @override
  State<AudioTrainingResultPage> createState() => _AudioTrainingResultPageState();
}

class _AudioTrainingResultPageState extends State<AudioTrainingResultPage> {
  @override
  void initState() {
    super.initState();
    // 页面初始化时自动保存训练记录
    WidgetsBinding.instance.addPostFrameCallback((_) => _autoSaveTrainingRecord());
  }

  void _autoSaveTrainingRecord() {
    print('Starting automatic audio training record creation...');
    final correctCount = widget.correctness.where((c) => c).length;
    final totalCount = widget.correctness.length;
    final duration = widget.responseTimes.fold(0, (sum, time) => sum + time);

    print('Audio training stats - correct: $correctCount, total: $totalCount, duration: $duration ms');

    final record = TrainingRecord(
      type: 'audio',
      correctCount: correctCount,
      totalCount: totalCount,
      durationMs: duration,
      timestamp: DateTime.now(),
    );

    print('Created audio training record: ${record.toString()}');
    context.read<TrainingHistoryBloc>().add(TrainingRecordAdded(record));
    print('Dispatched TrainingRecordAdded event for audio training');
  }

  @override
  Widget build(BuildContext context) {
    final correctCount = widget.correctness.where((c) => c).length;
    final totalCount = widget.correctness.length;
    final accuracy = totalCount > 0 ? (correctCount / totalCount) * 100 : 0;
    final duration = widget.responseTimes.fold(0, (sum, time) => sum + time);
    final minutes = duration ~/ 60000;
    final seconds = (duration % 60000) ~/ 1000;

    return Scaffold(
      appBar: AppBar(
  title: const Text('训练结果'),
  leading: IconButton(
    icon: const Icon(Icons.arrow_back),
    onPressed: () => Navigator.popUntil(context, (route) => route.isFirst),
  ),
),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(8), // 最小化页面内边距
          child: Column(
            children: [
              const SizedBox(height: 8), // 减少顶部间距
              _buildResultIndicator(accuracy.toDouble()),
              const SizedBox(height: 8), // 减少指示器与网格间距
              _buildStatsGrid(correctCount, totalCount, minutes, seconds),
              const SizedBox(height: 12), // 减少网格与按钮间距
              ElevatedButton.icon(
                onPressed: () => Navigator.popUntil(context, (route) => route.isFirst), 
                icon: const Icon(Icons.check_circle),
                label: const Text('记录已自动保存，返回训练'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), // 减小按钮内边距
                  textStyle: const TextStyle(fontSize: 14), // 减小按钮文字
                ),
              ),
              const SizedBox(height: 8), // 减少底部间距
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildResultIndicator(double accuracy) {
    return Column(
      children: [
        Text(
          '${accuracy.toStringAsFixed(1)}%',
          style: TextStyle(
            fontSize: 72,
            fontWeight: FontWeight.bold,
            color: accuracy >= 80 ? Colors.green : accuracy >= 60 ? Colors.orange : Colors.red,
          ),
        ),
        const SizedBox(height: 16),
        Text(
          accuracy >= 80 ? '太棒了！' : accuracy >= 60 ? '继续努力！' : '加油哦！',
          style: const TextStyle(fontSize: 24, color: Colors.grey),
        ),
      ],
    );
  }

  Widget _buildStatsGrid(int correct, int total, int minutes, int seconds) {
    // 根据屏幕宽度动态调整列数
    final isWideScreen = MediaQuery.of(context).size.width > 380;
    return GridView.count(
      shrinkWrap: true,
      crossAxisCount: isWideScreen ? 2 : 1, // 窄屏单列，宽屏双列
      crossAxisSpacing: 2,  // 最小化水平间距
      mainAxisSpacing: 2,   // 最小化垂直间距
      childAspectRatio: isWideScreen ? 1.333 : 1.333, // 宽屏更扁，窄屏更长
      children: [
        _buildStatCard(Icons.check, '正确题数', '$correct/$total'),
        _buildStatCard(Icons.timer, '用时', '${minutes > 0 ? '${minutes}分' : ''}${seconds > 0 ? '${seconds}秒' : minutes == 0 ? '0秒' : ''}'),
        _buildStatCard(Icons.trending_up, '正确率', '${(correct/total*100).toStringAsFixed(1)}%'),
        _buildStatCard(Icons.insights, '平均反应', '${(widget.responseTimes.fold(0, (sum, t) => sum + t) / widget.responseTimes.length).toStringAsFixed(0)}ms'),
      ],
    );
  }

  Widget _buildStatCard(IconData icon, String title, String value) {
    return Card(
      elevation: 1, // 减小阴影厚度
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 5), // 最小内边距
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min, // 设置最小主轴尺寸
          children: [
            Icon(icon, size: 18, color: Colors.blue), // 极小图标
            const SizedBox(height: 1), // 微小白间距
            Text(title, style: const TextStyle(fontSize: 10, color: Colors.grey)), // 小号标题
            const SizedBox(height: 1), // 微小白间距
            Text(value, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)), // 小号数值
          ],
        ),
      ),
    );
  }


  

}